<template>
  <div>
    <div>
      <p v-html="state.output" id="outputRef"></p>
    </div>
  </div>
</template>

<script setup lang="ts">
import {marked} from "marked";


const state = reactive({
  streamURL: '/sse',
  markdown: '# 这里是 ChatGpt，我可以帮助您快速生成自然语言文本。',
  delay: 50,
  output: '',
})
const outputRef = ref()
const printText = async () => {
  let i = 0;
  while (i < state.markdown.length) {
    state.output += state.markdown[i];
    // console.log('-outputRef.vlaue---',outputRef.vlaue)
    // outputRef.vlaue
    let ele = document.getElementById('outputRef')
    if (!ele) return
    ele.innerHTML = marked(state.output).replace(/\r\n/g, "<br>");
    i++;
    await new Promise((resolve) => setTimeout(resolve, state.delay));
  }
}
const startStream = () => {
  const eventSource = new EventSource(state.streamURL);

  eventSource.onmessage = (event) => {
    // 处理接收到的数据，这里假定服务器发送的事件数据为字符串类型
    if (event.data.startsWith("data: ")) {
      state.markdownData += event.data.slice(6); // 切掉"data: "前缀
      printText();
    }
  };

  eventSource.onerror = (event) => {
    // 处理 SSE 错误情况
    console.error("Failed to retrieve data through SSE: ", event);
    eventSource.close();
  };
}

onMounted(() => {
  // printText()
  startStream()
})
</script>

<style scoped>

</style>